﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace mesoBoard.Data.Repositories
{
    public class PostRepository : IPostRepository
    {
        private mbEntities db;

        public PostRepository(mbEntities mbDataContext)
        {
            this.db = mbDataContext;
        }

        public void CreatePost(Post ThePost)
        {
            db.Posts.AddObject(ThePost);
            db.SaveChanges();
        }

        public Post GetPost(int PostID)
        {
            return db.Posts.FirstOrDefault(x => x.PostID == PostID);
        }

        public Post GetAuthorPost(int ThreadID)
        {
            return db.Threads.FirstOrDefault(x => x.ThreadID == ThreadID).Posts.OrderBy(x => x.Date).First();
        }

        public void SubmitChanges()
        {
            db.SaveChanges();
        }

        public Post GetUserLastPost(int UserID)
        {
            return db.Posts.Where(x => x.UserID == UserID).OrderByDescending(x => x.Date).FirstOrDefault();
        }

        public IEnumerable<Post> GetAllPosts()
        {
            return db.Posts.AsEnumerable();
        }

        public void UpdatePost(Post ThePost)
        {
            if (ThePost.EntityKey == null)
                ThePost.EntityKey = ((Post)db.GetObjectByKey(new System.Data.EntityKey("mbEntities.Posts", "PostID", ThePost.PostID))).EntityKey;


            db.Posts.ApplyCurrentValues(ThePost);
            db.SaveChanges();
        }

        public IEnumerable<Post> GetPosts(int ThreadID)
        {
            return db.Posts.Where(x => x.ThreadID == ThreadID);
        }

        public void DeletePost(int PostID)
        {
            Post ThePost = db.Posts.FirstOrDefault(x => x.PostID == PostID);
            Thread TheThread = ThePost.Thread;
            if (TheThread.LastPostID == PostID)
            {
                TheThread.LastPostID = TheThread.Posts.OrderByDescending(x => x.Date).ElementAt(1).PostID;
            }
            db.SaveChanges();
            db.Posts.DeleteObject(ThePost);
            db.SaveChanges();
        }

        public int TotalPosts()
        {
            return db.Posts.Count();
        }
    }
}
